package fr.thelem.gestiondemandesthelem.service.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * Classe permettant d'accéder aux properties, qu'elles proviennent des modules
 * jboss ou du jar.
 */
public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

	@SuppressWarnings("rawtypes")
	private Map propertiesMap;
	// Default as in PropertyPlaceholderConfigurer
	private int springSystemPropertiesMode = PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK;

	/**
	 * Workaround: PropertyPlaceholderConfigurer.systemPropertiesMode is not
	 * directly accessible
	 * 
	 * @param systemPropertiesMode
	 *            systemPropertiesMode
	 */
	@Override
	public void setSystemPropertiesMode(final int systemPropertiesMode) {
		super.setSystemPropertiesMode(systemPropertiesMode);
		this.springSystemPropertiesMode = systemPropertiesMode;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void processProperties(
			final ConfigurableListableBeanFactory beanFactory,
			final Properties props) throws BeansException {
		super.processProperties(beanFactory, props);

		this.propertiesMap = new HashMap();
		for (final Object key : props.keySet()) {
			final String keyStr = key.toString();
			final String valueStr = this.resolvePlaceholder(keyStr, props,
					this.springSystemPropertiesMode);

			this.propertiesMap.put(keyStr, valueStr);
		}
	}

	/**
	 * Récupère la valeur d'une property à partir de sa clé
	 * 
	 * @param name
	 *            clé
	 * @return valeur
	 */
	public String getProperty(final String name) {
		return (String) this.propertiesMap.get(name);
	}

}
